<?php
namespace Openapi\Controller;
use Think\Controller;
class TrackingController extends CommonController {
	/**
	*上传单个订单物流单号，如某个物流单号已经上传，则覆盖之前上传的
	*@param $mid 商户ID
	*@param $site_id 网站ID
	*@param $oid  平台订单号
	*@param $tracking_company  物流公司代号
	*@param $tracking_number 运单号
	*@param string hash_info 验证信息 sha256  $mid.$site_id.$oid.$tracking_company.$tracking_number.$key
	*/
	public function upload($mid="",$site_id="",$oid="",$tracking_company="",$tracking_number="",$hash_info=""){
		$result['status']=0;		
		if(!parent::prepare($mid,$site_id,$oid)){
		$result['info']="transaction not found";
		$this->ajaxReturn($result);
		}
	
		//判断交易状态	待支付，已取消和支付拒绝的交易不得上传运单号
		if($this->order_info['order_status'] == 1 ||
		$this->order_info['order_status'] == 5 ||
		$this->order_info['order_status'] == 6
		){
		$result['info']="invalid order status";
		$this->ajaxReturn($result);			
		}
		
		//验证物流公司是否支持
		$oop=M("tracking");
		$con['tk_company']=$tracking_company;
		$list=$oop->where($con)->find();
		if(!$list){
		$result['info']="tracking company not allowed";
		$this->ajaxReturn($result);				
		}
		
		//运单号是否存在
		if($tracking_number==""){
		$result['info']="tracking number cannot be null";
		$this->ajaxReturn($result);					
		}
		
		//hash验证
		$hash_data=hash("sha256",$mid.$site_id.$oid.$tracking_company.$tracking_number.$this->order_info['site_key']);
		if($hash_info!=$hash_data){
		$result['info']="invalid request";
		$this->ajaxReturn($result);				
		}
		
		$data['dv_oid']=$this->order_info['order_id'];
		$data['dv_tk_id']=$list['tk_company'];
		$data['dv_number']=$tracking_number;
		//如果以上都没有问题 查看运单号是否已经上传过，如果上传过，则更像，反之，则添加
		if($this->order_info['dv_oid']){
		$data['dv_id']=$this->order_info['dv_id'];	
		//dump($data);
		$re=M("delivery")->save($data);
		//echo M("delivery")->_sql();
		}else{
		//dump($data);
		$re=M("delivery")->add($data);	
		}
		if($re){
		$result['status']=1;	
		$result['info']="upload tracking success";
		$this->ajaxReturn($result);						
		}else{
		$result['info']="upload tracking failed";
		$this->ajaxReturn($result);						
		}
	}
}